import socket
import json
from cryptography.fernet import Fernet
import os
import sys
import time
MCAST_GRP = '224.1.1.1' # 组播地址
MCAST_PORT = 50050 # 端口号
key_path = os.path.realpath(__file__).replace("server.py","")+"key"
netcastinfo_path = os.path.realpath(__file__).replace("server.py","")+"netcastinfo"

def encrypt(key, s):
    cipher = Fernet(key)
    return cipher.encrypt(s.encode()).decode()


with open(key_path, "rb") as f:
    key = f.read()
with open(netcastinfo_path, "r") as f:
    netcast_name = f.read()

ip_str = os.popen("ip address show {} |grep \"inet \"".format(netcast_name))
try:
    net_ip = ip_str.read().split()[1].split("/")[0]
except:
    sys.exit("I can't read the IP address,Perhaps there was an error in the network card name input,Please double-check.")

print(net_ip)
# Data to be written
dictionary = {
    "version": "0.1",
    "self_ip": "",
    "user_name": "ll"
}
dictionary["self_ip"] = net_ip
# Serializing json
json_object = json.dumps(dictionary, indent=4)



data = encrypt(key,json_object)
# 创建 UDP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

# 设置组播 TTL，这里设置为 1，表示仅限于本地网络
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
while True:
    # 发送数据报
    sock.sendto(data.encode(), (MCAST_GRP, MCAST_PORT))
    time.sleep(10)
